package phototransfer.model.udp;

import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class BroadcastSender {
   public static final String TAG = "BroadcastSender";
   private final byte[] mBuffer = new byte[256];
   private ScheduledExecutorService scheduledExecutorService;
   private int mServerPort = 8888;
   private DatagramSocket mDatagramSocketClient;
   private static BroadcastSender sInstance;

   public static BroadcastSender getInstance() {
      Class var0 = BroadcastSender.class;
      synchronized(BroadcastSender.class) {
         if (null == sInstance) {
            Class var1 = BroadcastSender.class;
            synchronized(BroadcastSender.class) {
               sInstance = new BroadcastSender();
            }
         }
      }

      return sInstance;
   }

   private BroadcastSender() {
   }

   public boolean startHeartBeat(long interval, int boardcastPort) {
      if (null != this.scheduledExecutorService) {
         return true;
      } else {
         this.mServerPort = boardcastPort;

         try {
            this.mDatagramSocketClient = new DatagramSocket();
            this.mDatagramSocketClient.setBroadcast(true);
         } catch (SocketException var5) {
            var5.printStackTrace();
         }

         this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
         this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            public void run() {
               try {
                  BroadcastSender.this.send(BroadcastSender.this.mBuffer, BroadcastSender.this.mBuffer.length);
               } catch (IOException var2) {
                  var2.printStackTrace();
                  Log.e("BroadcastSender", "startHeartBeat: ", var2);
               }

            }
         }, 0L, interval, TimeUnit.MILLISECONDS);
         return true;
      }
   }

   public void send(byte[] buf, int len) throws IOException {
      DatagramPacket sendPacket = new DatagramPacket(buf, len, InetAddress.getByName("255.255.255.255"), this.mServerPort);
      this.mDatagramSocketClient.send(sendPacket);
   }

   public void stopHeartBeat() {
      if (null != this.mDatagramSocketClient) {
         this.mDatagramSocketClient.close();
         this.mDatagramSocketClient = null;
      }

      if (null != this.scheduledExecutorService) {
         this.scheduledExecutorService.shutdownNow();
         this.scheduledExecutorService = null;
      }

   }

   public void startHeartBeat() {
      this.startHeartBeat(200L, 8888);
   }
}
